package cn.com.zpark;

import cn.com.zpark.utils.JDBCUtils01;
import cn.com.zpark.utils.JDBCUtils02;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @PackageName: cn.com.zpark
 * @ClassName: JDBC_04_Transaction
 * @Description:JDBC事务
 * @author: RZS
 * @date: 2021/10/27  17:54
 */
public class JDBC_04_Transaction {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement stat1 = null;
        PreparedStatement stat2 = null;
        ResultSet res = null;

        try {
            // 获取连接
            conn = JDBCUtils02.getConn();

            // 开启事务
            conn.setAutoCommit(false);// 关闭自动提交

            // 编写sql
            String sql1 = "update user set money=? where id=?";// 张三 +1000
            String sql2 = "update user set money=? where id=?";// 李四 -1000
            // 获取PreparedStatement对象
            stat1 = conn.prepareStatement(sql1);
            stat2 = conn.prepareStatement(sql2);
            // 设置stat1占位符
            stat1.setDouble(1, 1000.0);
            stat1.setInt(2, 1);
            // 设置stat2占位符
            stat2.setDouble(1, 3000.0);
            stat2.setInt(2, 2);


            // 执行sql
            stat1.executeUpdate();
            int num = 2/0;
            stat2.executeUpdate();

            // 提交事务
            conn.commit();

        } catch (Exception e) {
            // 回滚事务
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            // 关闭连接
            // JDBCUtils01.close(null, stat, conn);
            JDBCUtils02.close(null, conn, stat1, stat2);
        }
    }
}















